package com.zg.common.core.service.support;

import com.baomidou.mybatisplus.core.toolkit.support.SFunction;
import lombok.extern.slf4j.Slf4j;

import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;

/**
 * 泛型转换工具类（解决SFunction通配符问题）
 */
@SuppressWarnings("unchecked")
@Slf4j
public class GenericUtils {

    /**
     * 将通配符SFunction转换为具体泛型
     */
    public static <T, R> SFunction<T, R> castSFunction(SFunction<?, ?> function,
                                                       Class<T> entityClass,
                                                       Class<R> returnType) {
        try {
            Type[] types = function.getClass().getGenericInterfaces();
            for (Type type : types) {
                if (type instanceof ParameterizedType) {
                    ParameterizedType pt = (ParameterizedType) type;
                    if (pt.getRawType() == SFunction.class) {
                        Type[] actualTypeArgs = pt.getActualTypeArguments();
                        if (actualTypeArgs != null && actualTypeArgs.length == 2 &&
                                actualTypeArgs[0].equals(entityClass) &&
                                actualTypeArgs[1].equals(returnType)) {
                            return (SFunction<T, R>) function;
                        }
                    }
                } else if (type instanceof Class) {
                    Class<?> clazz = (Class<?>) type;
                    if (clazz == SFunction.class) {
                        // 处理没有泛型参数的情况
                        return (SFunction<T, R>) function;
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        throw new ClassCastException("SFunction类型不匹配");
    }

}
